package com.nami.gate.dubbo;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.nami.gate.api.request.message.DownMsgBatchReq;
import com.nami.gate.api.request.message.DownMsgRequest;
import com.nami.gate.api.service.RemoteDownMsgRecvService;
import com.nami.gate.cache.LocalChannelCache;
import com.nami.gate.utils.JsonUtils;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * rpc消费
 * 2024-12-08
 * 描述：
 *
 * @Author: lbc
 * @Date: 2023-07-16 18:35
 * @email: 594599620@qq.com
 * @Description: keep coding
 */
@Slf4j
@DubboService
@Service
@Deprecated
public class RemoteDownMsgRecvServiceImpl implements RemoteDownMsgRecvService {

    @Override
    public boolean flushChannel(DownMsgRequest request) {
        TimeInterval timer = DateUtil.timer();
        log.info("[flushPacket] 发送消息 identityNo={} msgId={}", request.getIdentityNo(), request.getMessageId());
        try {
            Channel channel = LocalChannelCache.get(request.getIdentityNo());
            if (channel == null) {
                // 如果为空，暂时为删除
                LocalChannelCache.removeAll(request.getIdentityNo());
                return Boolean.FALSE;
            }
            channel.writeAndFlush(request.getPacket());
        } catch (Exception e) {
            log.error("[flushPacket] 发送消息失败：", e);
            return Boolean.FALSE;
        }
        log.info("[flushPacket]【{}】发送消息成功：use{}ms", request.getIdentityNo(), timer.interval());
        return Boolean.TRUE;
    }

    @Override
    public void flushMore(DownMsgBatchReq request) {
        TimeInterval timer = DateUtil.timer();
//        log.info("[flushMore] 批量发送 dto:{}", JsonUtils.toJsonString(request));

        List<String> error = new ArrayList<>();

        List<String> identityNos = request.getIdentityNos();
        if (CollectionUtil.isEmpty(identityNos)) {
            return;
        }
        for (String identityNo : identityNos) {
            try {
                Channel channel = LocalChannelCache.get(identityNo);
                channel.writeAndFlush(request.getPacket());
            } catch (Exception e) {
                log.error("[flushMore] 发送消息失败:", e);
                error.add(identityNo);
            } // end if catch exception
        } // end for loop

        log.info("[flushMore] 群消息发送完毕 总数={}, 失败数：{}, use:{}ms", identityNos.size(), error.size(), timer.interval());
    }


}
